package com.css.fxfzfxqh.common.rest;

import cn.hutool.crypto.symmetric.Vigenere;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.css.fxfzfxqh.common.rest.model.bo.*;
import com.css.fxfzfxqh.common.rest.model.bo.ysx.*;
import com.css.fxfzfxqh.common.rest.model.param.*;
import com.css.fxfzfxqh.common.rest.model.vo.ysx.DestructiveStateVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.exceptions.BizException;
import com.css.fxfzfxqh.common.rest.model.param.JcDataVersionPageParam;
import com.css.fxfzfxqh.common.rest.model.param.JcsjDataViewParam;
import com.css.fxfzfxqh.common.rest.model.param.JcsjVersionPageParam;
import com.css.fxfzfxqh.modules.buildings.definitiveEvaluation.casualtiesDE.param.SysDataVersionPageParam;
import com.css.fxfzfxqh.modules.lifelineEngineering.param.SmxDataParam;
import com.css.fxfzfxqh.modules.lifelineEngineering.param.UploadShpParam;
import com.css.fxfzfxqh.modules.seismicHazardData.param.psHazard.ListByRangeParam;
import com.css.fxfzfxqh.util.PlatformObjectUtils;
import com.css.fxfzfxqh.util.PlatformSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * 基础数据api调用
 */
@RestController
@Slf4j
@Component
public class JcsjRestManager {

    @Autowired
    private RestTemplate restTemplate;
    // 查询人口网格版本信息接口列表接口url
    private static final String POPUATION_VERSION_PAGE_URL = "datacenter/sysDataVersion/page";
    // 查询版本信息接口列表接口url
    private static final String VERSION_PAGE_URL = "datacenter/sysDataVersion/dzzhfxpgyqhxt/page";
    // 查询元数据信息接口
    private static final String GET_META_DATA_BY_VERSION_CODE_URL = "datacenter/sysDataVersion/dzzhfxpgyqhxt/getMetaDataByVersionCode";
    // 查询数据视图接口
    private static final String QUERY_DATA_VIEW_URL = "datacenter/sysDataVersion/dzzhfxpgyqhxt/queryDataView";
    // 查询数据视图接口不分页
    private static final String QUERY_DATA_VIEW_LIST_URL = "datacenter/sysDataVersion/dzzhfxpgyqhxt/queryDataViewList";
    // 导出接口
    private static final String DATA_EXPORT_URL = "datacenter/sysDataVersion/dataExport";
    private static final String EXPORT_DATA_VIEW_URL = "datacenter/sysDataVersion/exportDataView";
    // 查询数据类别接口
    private static final String GET_CHILDREN_BY_DICT_CODE = "test/dictItems/getDictItemByDictCode";
    // 根据空间数据查询人口公里网格
    private static final String JC_POPULATION_GRID_GET_BY_GEOM = "datacenter/jcPopulationGrid/dzzhfxpgyqhxt/getByGeom";
    private static final String JC_POPULATION_GRID_GET_BY_PROVINCE = "datacenter/jcPopulationGrid/dzzhfxpgyqhxt/getByProvince";
    private static final String LD = "jcLd/dzzhfxpgyqhxt/listAsPost";
    private static final String LD1 = "jcLd/dzzhfxpgyqhxt/listAsPost1";
    private static final String ListByGeomText = "districtQuery/queryProvinceCityCountyNameCodeListByGeomText";
    private static final String PGA = "jcPga/dzzhfxpgyqhxt/listAsPost";
    private static final String PGA1 = "jcPga/dzzhfxpgyqhxt/listAsPost1";
    private static final String getByProvinceByIds = "datacenter/jcBoua5/getByProvinceByIds";
    private static final String getByCitByIds = "datacenter/jcBoua5/getByCitByIds";
    private static final String getByCountyByName = "datacenter/jcBoua5/getByCountyByName";
    private static final String getGeomByProvinceCode = "datacenter/jcBoua2/getGeomByCode";
    private static final String getGeomByCityCode = "datacenter/jcBoua4/getGeomByCode";
    private static final String getGeomByCountyCode = "datacenter/jcBoua5/getGeomByCode";
    private static final String getUnionGeomByCode = "datacenter/jcBoua5/getUnionGeomByCodeList";

    private static final String GEOGRAPHIC_LOCATION_BY_RANGE = "chinaGrid/listByRange";
    private static final String GET_CHINA_GRID_ID_NEW = "chinaGrid/getChinaGridIdNew";

    private static final String GETPGA = "basicLibrary/getByRegion";

    private static final String GET_LIFELINE = "lifelineEngineering/getLifelineDataSource";
    private static final String GET_ANALYSIS_BY_TYPE_AND_ID = "lifelineEngineering/getAnalysisByVersionId";
    private static final String GET_REPEAT_DATA = "lifelineEngineering/getRepeatData";
    private static final String GET_VERSION_CODE = "lifelineEngineering/getVersionCode";
    private static final String GET_BY_TYPE_AND_VERSION_ID = "lifelineEngineering/getByTypeAndVersionId";
    private static final String DELETE_BY_TYPE_AND_VERSION_ID = "lifelineEngineering/deleteByTypeAndVersionId";
    private static final String DELETE_BY_TYPE_AND_ID = "lifelineEngineering/deleteByTypeAndId";
    private static final String UPDATE_BY_ID = "lifelineEngineering/updateById";
    private static final String UPLOAD_FILE = "attachment/uploadFile";
    private static final String GET_BY_TYPE_AND_LIFELINE_ID_AND_INTENSITY = "lifelineFoundationLibrary/getByTypeAndLifelineIdAndIntensity";

    private static final String SAVE_LIFELINE_DATA = "lifelineEngineering/uploadShp";
    private static final String GET_BY_CODE = "base/dicts/getValidDictItemsByDictCode";
    private static final String IMPORT_HUB_BUILDING = "bubBuilding/importHubBuilding";
    private static final String GET_VECTOR_DATA_IDS_BY_VERSION_ID = "lifelineEngineering/getVectorDataIdsByVersionId";
    private static final String GET_GDP = "datacenter/fxqh/getGdp";

    /**
     * 获取基础请求路径
     *
     * @return
     */
    private static String getBaseUrl(String apiUrl) throws BizException {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String jcsjRestUrl = configGroup.getProperty("jcsjRestUrl");
        if (StringUtils.isBlank(jcsjRestUrl)) {
            throw new BizException("配置文件未发现基础数据系统接口URL");
        }
        if (!StringUtils.endsWith(jcsjRestUrl, "/")) {
            jcsjRestUrl += "/";
        }
        return jcsjRestUrl + apiUrl;
    }

    /**
     * 获取基础请求路径-承灾体易损性系统
     *
     * @return
     */
    private static String getBaseUrl2(String apiUrl) throws BizException {
        Properties configGroup = PropsHelper.loadProps("slw-config.properties");
        String jcsjRestUrl = configGroup.getProperty("ysxRestUrl");
        if (StringUtils.isBlank(jcsjRestUrl)) {
            throw new BizException("配置文件未发现基础数据系统接口URL");
        }
        if (!StringUtils.endsWith(jcsjRestUrl, "/")) {
            jcsjRestUrl += "/";
        }
        return jcsjRestUrl + apiUrl;
    }

    /**
     * 格式化参数为get方式的请求参数字符串
     *
     * @param param
     * @param <T>
     * @return
     */
    private static <T> String buildGetMethodParam(T param) {
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(param, SerializerFeature.WriteDateUseDateFormat));
        StringBuilder str = new StringBuilder("?");
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            str.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }

        String s = str.toString();
        if (s.endsWith("?")) {
            return StringUtils.removeEnd(s, "?");
        } else {
            return StringUtils.removeEnd(s, "&");
        }
    }

    /**
     * 查询版本信息列表接口
     *
     * @param param
     */
    public JcsjVersionPageBo versionPage(JcsjVersionPageParam param) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl(VERSION_PAGE_URL) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, JcsjVersionPageBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            throw e;
        }
    }

    /**
     * 查询元数据信息接口
     *
     * @param versionCode 版本号
     */
    public JcsjVersionMetaInfoBo getMetaDataByVersionCode(String versionCode) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl(GET_META_DATA_BY_VERSION_CODE_URL) + "/" + versionCode;
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, JcsjVersionMetaInfoBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", versionCode);
            throw e;
        }
    }

    /**
     * 获取指定范围内的GDP
     */
    public  JSONObject getGdp(String geom,String dataVersion) throws Exception {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        JSONObject param = new JSONObject();
        param.put("geomText", geom);
        param.put("dataVersion", dataVersion);
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(GET_GDP);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        } finally {
            stopWatch.stop();
            log.debug("调用基础数据GDP接口,url：{},用时：{}s,参数:[geomText：{},dataVersion：{}]", url, stopWatch.getTotalTimeSeconds(), geom);
        }
    }
    /**
     * 查询数据视图接口
     *
     * @param param 查询参数
     * @return
     * @throws BizException
     */
    public JcsjDataViewBo queryDataView(JcsjDataViewParam param) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl(QUERY_DATA_VIEW_LIST_URL) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, JcsjDataViewBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            throw e;
        }
    }

    /**
     * 版本数据导出
     *
     * @param idList
     * @return
     * @throws BizException
     */
    public Resource versionDataExport(List<String> idList) throws BizException {
        HttpEntity<List<String>> entity = new HttpEntity<>(idList, buildBaseHeaders());
        String url = getBaseUrl(DATA_EXPORT_URL);
        try {
            ResponseEntity<Resource> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, Resource.class);
            return exchange.getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", idList);
            throw e;
        }
    }

    /**
     * 数据视图导出
     *
     * @param param 参数
     * @return
     * @throws BizException
     */
    public Resource exportDataView(JcDataVersionPageParam param) throws BizException {
        HttpEntity<JcDataVersionPageParam> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(EXPORT_DATA_VIEW_URL);
        try {
            ResponseEntity<Resource> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, Resource.class);
            return exchange.getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            throw e;
        }
    }

    /**
     * 查询数据类别接口
     * 根据父级code查询子级信息
     *
     * @param code
     * @return
     */
    public JcsjDataTypeBo getDictItemByDictCode(String code) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl(GET_CHILDREN_BY_DICT_CODE) + "/" + code;
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, JcsjDataTypeBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", code);
            throw e;
        }
    }

    //    @GetMapping("getJcPopulationGridGetByGeom")
//    public JcPopulationGridBo getJcPopulationGridGetByGeom(String geom,String dataVersion) throws BizException {
//        HttpEntity<String> entity = new HttpEntity<>(geom, buildBaseHeaders());
//        String url = getBaseUrl(JC_POPULATION_GRID_GET_BY_GEOM);
//        try {
//            return restTemplate.exchange(url, HttpMethod.POST, entity, JcPopulationGridBo.class).getBody();
//        } catch (RestClientException e) {
//            log.info("error -> url: {}", url);
//            log.info("error -> param: {}", geom);
//            throw e;
//        }
//    }
    public JcPopulationGridBo getJcPopulationGridGetByGeom(Map<String,String> paramMap) throws BizException {
        HttpEntity<Map<String,String>> entity = new HttpEntity<>(paramMap, buildBaseHeaders());
        String url = getBaseUrl(JC_POPULATION_GRID_GET_BY_GEOM);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, JcPopulationGridBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", paramMap);
            throw e;
        }
    }

    public JcPopulationGridByProvinceBo getJcPopulationGridGetByProvince(String province, String city, String county) throws BizException {
        HttpEntity<String> entity = new HttpEntity<>(buildBaseHeaders());
        Map<String, String> param = new HashMap<>();
        param.put("province", province);
        param.put("city", city);
        param.put("county", county);
        String url = getBaseUrl(JC_POPULATION_GRID_GET_BY_PROVINCE) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, JcPopulationGridByProvinceBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", province);
            throw e;
        }
    }

    public JcBoua5getByProvinceByIdsBo getByProvinceByIds(List<String> list) throws BizException {
        HttpEntity<List<String>> entity = new HttpEntity<>(list, buildBaseHeaders());
        String url = getBaseUrl(getByProvinceByIds);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, JcBoua5getByProvinceByIdsBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public JcBoua5getByProvinceByIdsBo getByCitByIds(List<String> list) throws BizException {
        HttpEntity<List<String>> entity = new HttpEntity<>(list, buildBaseHeaders());
        String url = getBaseUrl(getByCitByIds);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, JcBoua5getByProvinceByIdsBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    //    @PostMapping("getByCountyByNames")
//    public JcBoua5getByProvinceByIdsBo getByCountyByNames(@RequestBody List<String> list) throws BizException {
    public JcBoua5getByCountyNameBo getByCountyByName(String name) throws BizException {
        HttpEntity<String> entity = new HttpEntity<>(name, buildBaseHeaders());
        String url = getBaseUrl(getByCountyByName);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, JcBoua5getByCountyNameBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public String getGeomByCode(String code, String type) throws BizException {
        HttpEntity<String> entity = new HttpEntity<>(code, buildBaseHeaders());
        String url = null;
        if ("1".equals(type)){
            url = getBaseUrl(getGeomByProvinceCode);
        }else if ("2".equals(type)){
            url = getBaseUrl(getGeomByCityCode);
        }else {
            url = getBaseUrl(getGeomByCountyCode);
        }
        try {
            JSONObject body = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
            if (body == null) {
                return null;
            }
            return (String) body.get("data");
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public String getUnionGeomByCodeList(List<String> codeList) throws BizException {
        HttpEntity<List<String>> entity = new HttpEntity<>(codeList, buildBaseHeaders());
        String url = getBaseUrl(getUnionGeomByCode);
        try {
            JSONObject body = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
            if (body == null) {
                return null;
            }
            return (String) body.get("data");
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    //    @PostMapping("getChinaGridIdNew")
    public GetChinaGridBo getChinaGridIdNew(String geomText, String province, String city, String county) throws BizException {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        JSONObject param = new JSONObject();
        param.put("geomText", geomText);
        param.put("province", province);
        param.put("city", city);
        param.put("county", county);
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(GET_CHINA_GRID_ID_NEW);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, GetChinaGridBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        } finally {
            stopWatch.stop();
            log.debug("调用基础数据全国格网接口,url：{},用时：{}s,参数:[geomText：{},province：{},city：{},county：{}]", url, stopWatch.getTotalTimeSeconds(), geomText, province, city, county);
        }
    }

    public ChinaGridBo getGeographicLocationByRange(ListByRangeParam param) throws BizException {
        long startTime = System.currentTimeMillis();
        HttpEntity<ListByRangeParam> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(GEOGRAPHIC_LOCATION_BY_RANGE);
        //设置超时时间
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(0);
        clientHttpRequestFactory.setReadTimeout(0);

        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            ChinaGridBo body = restTemplate.exchange(url, HttpMethod.POST, entity, ChinaGridBo.class).getBody();
            long endTime = System.currentTimeMillis();
            log.info("远程调用用时:{}", (endTime - startTime) + "ms");
            return body;
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    /**
     * 构建一个基础的请求头
     *
     * @return
     */
    private static HttpHeaders buildBaseHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "dzzhfxpgyqhxt");
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    private static HttpHeaders buildBaseHeaders1() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", PlatformSessionUtils.getUserId());
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    //通过省市县获取基础数据的ld的数据
    public JcLDBo getLDList(String province, String city, String county, String version) throws BizException {
        JSONObject param = new JSONObject();
        param.put("province", province);
        param.put("city", city);
        param.put("county", county);
        if (!"".equals(version)) {
            param.put("dataVersion", version);
        }
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(LD);
        System.out.println(url);
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplateDgDevice.setRequestFactory(clientHttpRequestFactory);
        try {
            JcLDBo body = restTemplateDgDevice.exchange(url, HttpMethod.POST, entity, JcLDBo.class).getBody();
            return body;
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", province);
            throw e;
        }
    }

    //通过空间数据获取基础数据的ld的数据
    public DistrictEntityBo getPCCByGeomText(String geom) throws BizException {
        JSONObject param = new JSONObject();
        param.put("geomText", geom);
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(ListByGeomText);
        System.out.println(url);
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplateDgDevice.setRequestFactory(clientHttpRequestFactory);
        try {
            DistrictEntityBo body = restTemplateDgDevice.exchange(url, HttpMethod.POST, entity, DistrictEntityBo.class).getBody();
            return body;
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    //通过空间数据获取基础数据的ld的数据
    public JcLDBo getLDList1(String geom, String version) throws BizException {
        JSONObject param = new JSONObject();
        param.put("extends10", geom);
        if (PlatformObjectUtils.isNotEmpty(version)) {
            param.put("dataVersion", version);
        }
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(LD1);
        System.out.println(url);
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplateDgDevice.setRequestFactory(clientHttpRequestFactory);
        try {
            JcLDBo body = restTemplateDgDevice.exchange(url, HttpMethod.POST, entity, JcLDBo.class).getBody();
            return body;
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    //获取
    public JcPgaBo getPagList(String province, String city, String county, String version) throws BizException {
        JSONObject param = new JSONObject();
        param.put("province", province);
        param.put("city", city);
        param.put("county", county);
        if (!"".equals(version)) {
            param.put("dataVersion", version);
        }
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(PGA);
        System.out.println(url);
        //设置超时时间
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            return restTemplateDgDevice.exchange(url, HttpMethod.POST, entity, JcPgaBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", province);
            throw e;
        }
    }

    //通过空间数据获取基础数据的pga的数据
    public JcPgaBo getPagList1(String geom, String version) throws BizException {
        JSONObject param = new JSONObject();
        param.put("extends10", geom);
        if (PlatformObjectUtils.isNotEmpty(version)) {
            param.put("dataVersion", version);
        }
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl(PGA1);
        System.out.println(url);
        //设置超时时间
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            return restTemplateDgDevice.exchange(url, HttpMethod.POST, entity, JcPgaBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public JSONObject populationVersionPage(SysDataVersionPageParam param) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl(POPUATION_VERSION_PAGE_URL) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class).getBody().getJSONObject("data");
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            throw e;
        }
    }

    //获取
    public JSONArray getPgaOfYsx(String province, String city, String county) throws BizException {
        JSONObject param = new JSONObject();
        param.put("province", province);
        param.put("city", city);
        param.put("county", county);
        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl2(GETPGA);
        System.out.println(url);
        //设置超时时间
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            return restTemplateDgDevice.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody().getJSONArray(
                    "data");
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", province);
            throw e;
        }
    }


    //获取
    public JSONObject getBasicLibraryPageForGet(String toUrl, JSONObject param) throws BizException {

        HttpEntity<JSONObject> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(toUrl) + buildGetMethodParam(param);
        System.out.println(url);
        //设置超时时间
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            return restTemplateDgDevice.exchange(url, HttpMethod.GET, entity, JSONObject.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param.toString());
            throw e;
        }
    }

    //获取
    public JSONObject getBasicLibraryPageForPost(String toUrl, JSONObject param) throws BizException {

        HttpEntity<JSONObject> entity = new HttpEntity<>(param, buildBaseHeaders());
        String url = getBaseUrl2(toUrl);
        System.out.println(url);
        //设置超时时间
        RestTemplate restTemplateDgDevice = new RestTemplate();
        SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
        clientHttpRequestFactory.setConnectTimeout(30000);
        clientHttpRequestFactory.setReadTimeout(30000);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        try {
            return restTemplateDgDevice.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param.toString());
            throw e;
        }
    }

    public YsxLifelineDataBo getLifelineDataSource(YsxDataSourcePageParam param) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(GET_LIFELINE) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, YsxLifelineDataBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            throw e;
        }
    }

    /**
     * 生命线查询详情
     *
     * @return
     */
    public SmxDetailsBo getAnalysisByVersionId(AnalysisParam param) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(GET_ANALYSIS_BY_TYPE_AND_ID) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, SmxDetailsBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    /**
     * 生命线-查询重复版本数据
     */
    public SmxVersionBo getRepeatData(UploadShpParam param) throws BizException {
        HttpEntity<UploadShpParam> entity = new HttpEntity<>(param, buildBaseHeaders1());
        String url = getBaseUrl2(GET_REPEAT_DATA);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity, SmxVersionBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    /**
     * 查询版本数据
     *
     * @param param
     * @return
     * @throws BizException
     */
    public SmxVersionInfoBo getVersionCode(UploadShpParam param) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(GET_VERSION_CODE) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, SmxVersionInfoBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    /**
     * 根据版本号查询
     *
     * @param param
     * @return
     * @throws BizException
     */
    public SmxVersionInfoBo getByTypeAndVersionId(SmxDataParam param) throws BizException {
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(GET_BY_TYPE_AND_VERSION_ID) + buildGetMethodParam(param);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, SmxVersionInfoBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    /**
     * 根据版本号删除  （删除整个版本）
     *
     * @param versionId
     * @throws BizException
     */
    public Integer deleteByTypeAndVersionId(String versionId) throws BizException {
        JSONObject param = new JSONObject();
        param.put("versionId", versionId);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(DELETE_BY_TYPE_AND_VERSION_ID) + buildGetMethodParam(param);
        try {
            JSONObject body = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class).getBody();
            return (Integer) body.get("code");
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public Integer deleteByTypeAndId(Integer type, String ids) throws BizException {
        HashMap<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("ids", ids);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(DELETE_BY_TYPE_AND_ID) + buildGetMethodParam(map);
        try {
            JSONObject body = restTemplate.exchange(url, HttpMethod.GET, entity, JSONObject.class).getBody();
            return (Integer) body.get("code");
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public Integer updateById(HashMap<Integer, Object> map) throws BizException {
        HttpEntity<HashMap<Integer, Object>> entity = new HttpEntity<>(map, buildBaseHeaders1());
        String url = getBaseUrl2(UPDATE_BY_ID);
        try {
            JSONObject body = restTemplate.exchange(url, HttpMethod.POST, entity, JSONObject.class).getBody();
            return (Integer) body.get("code");
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }


    /**
     * 上传文件
     *
     * @return
     * @throws BizException
     */
    public AttachmentInfoBo uploadFile(List<MultipartFile> files) throws Exception {
        String url = getBaseUrl2(UPLOAD_FILE);
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<>();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        AttachmentInfoBo result = null;
        try {
            for (MultipartFile file : files) {
                ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
                    @Override
                    public String getFilename() {
                        return file.getOriginalFilename();
                    }
                };
                paramsMap.add("file", resource);
            }
            // 构造请求的实体。包含body和headers的内容
            HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(paramsMap, headers);
            result = restTemplate.postForEntity(url, request, AttachmentInfoBo.class).getBody();
        } catch (Exception e) {
            log.error("上传文件失败：", e);
        }
        return result;
    }

    public DestructiveStateVo getByTypeAndLifelineIdAndIntensity(String id, Integer type, Integer range) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("type", type);
        map.put("range", range);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(GET_BY_TYPE_AND_LIFELINE_ID_AND_INTENSITY) + buildGetMethodParam(map);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, DestructiveStateVo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public UploadShpBo uploadShp(UploadShpParam param) throws Exception {
        HttpEntity<UploadShpParam> entity = new HttpEntity<>(param, buildBaseHeaders1());
        String url = getBaseUrl2(SAVE_LIFELINE_DATA);
        try {
            return restTemplate.exchange(url, HttpMethod.POST, entity,UploadShpBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public DictItemBo getByCode(String dictCode) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("dictCode", dictCode);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(GET_BY_CODE) + buildGetMethodParam(map);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, DictItemBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }

    public Integer importHubBuilding(MultipartFile file, Integer type, String province, String city, String county, Integer cover, String id) throws Exception {
        String url = getBaseUrl2(IMPORT_HUB_BUILDING);
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<>();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("Authorization", PlatformSessionUtils.getUserId());
        try {
            ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename();
                }
            };
            paramsMap.add("file", resource);
            paramsMap.add("type", type);
            paramsMap.add("province", province);
            paramsMap.add("city", city);
            paramsMap.add("county", county);
            paramsMap.add("cover", cover);
            paramsMap.add("id", id);
            // 构造请求的实体。包含body和headers的内容
            HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(paramsMap, headers);
            JSONObject body = restTemplate.exchange(url,HttpMethod.POST, request, JSONObject.class).getBody();
            return (Integer) body.get("code");
        } catch (Exception e) {
            log.error("上传文件失败：", e);
            return 500;
        }
    }

    /**
     * 根据版本号查询变电站或基站id
     * @param versionId
     * @param type
     * @return
     */
    public VectorDataIdsBo getVectorDataIdsByVersionId(String versionId, Integer type) throws Exception{
        HashMap<String, Object> map = new HashMap<>();
        map.put("versionId", versionId);
        map.put("type", type);
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(buildBaseHeaders());
        String url = getBaseUrl2(GET_VECTOR_DATA_IDS_BY_VERSION_ID) + buildGetMethodParam(map);
        try {
            return restTemplate.exchange(url, HttpMethod.GET, entity, VectorDataIdsBo.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            throw e;
        }
    }
}
